<template>
  <div class="scheduling-container">
    <div v-if="!haveScheduling">
      <el-card class="box-card" style="width: 100%;height: 100%">
        <el-empty description="您当前时间暂无排班记录" :image-size="100">
          <template #description>
            <span style="font-size: 16px; color: #909399;">您当前时间暂无排班记录</span>
          </template>
        </el-empty>
      </el-card>
    </div>

    <div v-if="haveScheduling" class="scheduling-content">
      <el-card class="current-info-card">
        <div class="current-info">
          <div class="info-item">
            <div class="label">当前叫号:</div>
            <div :class="['value', currentHao === 0 ? 'waiting' : 'active']">
              {{ currentHao === 0 ? '等待叫号' : currentHao }}
            </div>
          </div>
          <div class="divider"></div>
          <div class="info-item">
            <div class="label">当前就诊:</div>
            <div :class="['value', currentZhen === 0 ? 'waiting' : 'active']">
              {{ currentZhen === 0 ? '等待就诊' : currentZhen }}
            </div>
          </div>
        </div>
      </el-card>

      <el-card class="patient-list-card">
        <template #header>
          <div class="card-header">
            <span>排队患者列表</span>
          </div>
        </template>

        <el-table
            :data="rankRecords"
            :row-style="{ height: '75px' }"
            height="650px"
            style="width: 100%"
            :striped="true"
            :border="true"
            highlight-current-row>
          <template #empty>
            <div class="empty-table">暂无取号排队用户</div>
          </template>

          <el-table-column prop="id" label="编号" width="80" align="center" />

          <el-table-column prop="order" label="次序" width="80" align="center">
            <template #default="scope">
              <span :class="{'current-order': scope.row.order === currentHao || scope.row.order === currentZhen}">
                {{ scope.row.order }}
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="patient.name" label="就诊人姓名" min-width="120" />

          <el-table-column label="就诊类型" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getVisitTypeTag(scope.row.type)">{{ getVisitTypeName(scope.row.type) }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="状态" width="120" align="center">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.state)" size="medium">
                {{ getStatusName(scope.row.state) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200" align="center">
            <template #default="scope">
              <div class="action-buttons">
                <el-button
                    v-if="scope.row.state == 5 || scope.row.state == 4"
                    type="primary"
                    @click="jiaoHao(scope.row)"
                    :disabled="currentZhen !== 0">
                  叫号
                </el-button>
                <el-button
                    v-if="scope.row.state == 5 || scope.row.state == 4"
                    type="danger"
                    @click="zhenduan(scope.row)"
                    :disabled="currentHao !== scope.row.order || currentZhen !== 0">
                  开始诊断
                </el-button>
                <el-button
                    v-if="scope.row.state == 3"
                    type="success"
                    @click="showJianchaDialog(scope.row)">
                  开检查
                </el-button>
                <el-button
                    v-if="scope.row.state == 3"
                    type="warning"
                    @click="dialogFormVisible=true">
                  诊断结束
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 诊断结束对话框 -->
    <el-dialog
        title="结束诊断"
        v-model="dialogFormVisible"
        width="500px"
        @close="clear">
      <el-form :model="form" label-position="top">
        <el-form-item label="诊断结果与医嘱">
          <el-input
              v-model="result"
              :rows="8"
              type="textarea"
              placeholder="请输入诊断结果与医嘱"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="jieshuzhenduan" :loading="submitting">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 开检查对话框 -->
    <el-dialog
        title="开检查"
        v-model="jianchaDialog"
        width="500px">
      <el-form :model="form" label-position="right" label-width="120px">
        <el-form-item label="检查名">
          <el-input v-model="form.name" placeholder="请输入检查项目名称"></el-input>
        </el-form-item>
        <el-form-item label="检查地址">
          <el-input v-model="form.address" placeholder="请输入检查地点"></el-input>
        </el-form-item>
        <el-form-item label="检查类型">
          <el-select v-model="form.type" placeholder="请选择检查类型" style="width: 100%">
            <el-option label="检验报告" :value="0"></el-option>
            <el-option label="检查报告" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="jianchaDialog = false">取 消</el-button>
          <el-button type="primary" @click="saveJiancha" :loading="submitting">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";

// 初始化数据
const haveScheduling = ref(false);
const currentHao = ref(0);
const currentZhen = ref(0);
const user = JSON.parse(sessionStorage.getItem("user") || '{}');
const rankRecords = ref([]);
const scheduling = ref({});
const submitting = ref(false);

onMounted(() => {
  initScheduling();
});

const initScheduling = () => {
  axios.get('scheduling/getNowScheduling', { params: { did: user.id } }).then(res => {
    if (res.data.code === 200) {
      scheduling.value = res.data.data;
      if (scheduling.value == null) {
        haveScheduling.value = false;
      } else {
        haveScheduling.value = true;
        initRankRecords();
      }
    } else {
      ElMessage.error(res.data.msg || '获取排班信息失败');
    }
  }).catch(error => {
    console.error("获取排班信息错误:", error);
    ElMessage.error('获取排班信息失败');
  });
};

const initRankRecords = () => {
  axios.get('rankRecord/getHaoAndZhen', { params: { sid: scheduling.value.id } }).then(res => {
    if (res.data.code === 200) {
      currentHao.value = res.data.data.hao;
      currentZhen.value = res.data.data.zhen;
    } else {
      ElMessage.error(res.data.msg || '获取当前挂号和诊断失败');
    }
  }).catch(error => {
    console.error("获取当前挂号和诊断错误:", error);
    ElMessage.error('获取当前挂号和诊断失败');
  });

  axios.get('rankRecord/getRankRecordsBySid', { params: { sid: scheduling.value.id } }).then(res => {
    if (res.data.code === 200) {
      rankRecords.value = res.data.data;
    } else {
      ElMessage.error(res.data.msg || '获取排队记录失败');
    }
  }).catch(error => {
    console.error("获取排队记录错误:", error);
    ElMessage.error('获取排队记录失败');
  });
};

// 操作
const jiaoHao = (val) => {
  if (currentZhen.value === 0) {
    axios.get('rankRecord/jiaohao', {
      params: {
        sid: scheduling.value.id,
        currentHao: currentHao.value,
        rid: val.id
      }
    }).then(res => {
      if (res.data.code === 200) {
        currentHao.value = val.order;
        initRankRecords();
        ElMessage.success('叫号成功');
      } else {
        ElMessage.error(res.data.msg || '叫号失败');
      }
    }).catch(error => {
      console.error("叫号错误:", error);
      ElMessage.error('叫号失败');
    });
  } else {
    ElMessage.error('当前有患者诊断中');
  }
};

const zhenduan = (val) => {
  if (currentHao.value === val.order) {
    axios.get('rankRecord/zhenduan', { params: { rid: val.id } }).then(res => {
      if (res.data.code === 200) {
        currentHao.value = 0;
        currentZhen.value = val.order;
        initRankRecords();
        ElMessage.success('开始诊断');
      } else {
        ElMessage.error(res.data.msg || '开始诊断失败');
      }
    }).catch(error => {
      console.error("开始诊断错误:", error);
      ElMessage.error('开始诊断失败');
    });
  } else {
    ElMessage.error('与当前叫号不符');
  }
};

// 诊断结束
const clear = () => {
  dialogFormVisible.value = false;
  jianchaDialog.value = false;
  form.value = {};
  result.value = ''
  submitting.value = false;
  initRankRecords();
};

const dialogFormVisible = ref(false);
const result = ref('');
const jieshuzhenduan = () => {
  if (!result.value.trim()) {
    ElMessage.warning('请输入诊断结果与医嘱');
    return;
  }

  submitting.value = true;
  axios.get('/rankRecord/jieshuzhenduan', {
    params: {
      sid: scheduling.value.id,
      currentZhen: currentZhen.value,
      result: result.value
    }
  }).then(res => {
    if (res.data.code === 200) {
      ElMessage.success('结束就诊成功');
      currentZhen.value = 0;
      initRankRecords();
      clear();
    } else {
      ElMessage.error(res.data.msg || '结束就诊失败');
    }
  }).catch(error => {
    console.error("结束就诊错误:", error);
    ElMessage.error('结束就诊失败');
  }).finally(() => {
    submitting.value = false;
  });
};

// 开检查
const showJianchaDialog = (val) => {
  form.value = {
    rankId: val.id,
    name: '',
    address: '',
    type: null
  };
  jianchaDialog.value = true;
};

const jianchaDialog = ref(false);
const formLabelWidth = '120px';
const form = ref({
  name: '',
  address: '',
  type: null
});

const saveJiancha = () => {
  if (!form.value.name || !form.value.address || form.value.type === null) {
    ElMessage.warning("请输入完整的信息");
    return;
  }

  submitting.value = true;
  axios.post('check_record/addJiancha', form.value).then(res => {
    if (res.data.code === 200) {
      ElMessage.success("开检查成功");
      clear();
    } else {
      ElMessage.error(res.data.msg || "开检查失败");
    }
  }).catch(error => {
    console.error("开检查错误:", error);
    ElMessage.error('开检查失败');
  }).finally(() => {
    submitting.value = false;
  });
};

// 辅助函数 - 获取状态显示
const getStatusName = (state) => {
  switch(state) {
    case 1: return '已完成';
    case 3: return '就诊中';
    case 4: return '正在叫号';
    case 5: return '已取号等待叫号';
    default: return '未知状态';
  }
};

// 辅助函数 - 获取状态标签类型
const getStatusType = (state) => {
  switch(state) {
    case 1: return 'success';
    case 3: return 'primary';
    case 4: return 'warning';
    case 5: return 'info';
    default: return '';
  }
};

// 辅助函数 - 获取就诊类型名称
const getVisitTypeName = (type) => {
  switch(type) {
    case 0: return '自费';
    case 1: return '北京医保';
    case 2: return '异地医保';
    default: return '未知类型';
  }
};

// 辅助函数 - 获取就诊类型标签类型
const getVisitTypeTag = (type) => {
  switch(type) {
    case 0: return 'danger';
    case 1: return 'success';
    case 2: return 'warning';
    default: return '';
  }
};
</script>

<style scoped>
.scheduling-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 50px 0;
}

.scheduling-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.current-info-card {
  height: auto !important;
  margin: 10px auto;
}

.current-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 30px;
  padding: 10px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.label {
  font-size: 18px;
  color: #606266;
  font-weight: bold;
}

.value {
  font-size: 40px;
  font-weight: bold;
  padding: 8px 16px;
  border-radius: 8px;
  min-width: 100px;
  text-align: center;
}

.waiting {
  background-color: #f0f0f0;
  color: #909399;
}

.active {
  background-color: #ecf5ff;
  color: #409eff;
}

.divider {
  width: 1px;
  height: 40px;
  background-color: #dcdfe6;
}

.patient-list-card {
  min-height: 700px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.action-buttons {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.current-order {
  background-color: #ecf5ff;
  color: #409eff;
  padding: 2px 8px;
  border-radius: 4px;
}

.empty-table {
  text-align: center;
  color: #909399;
  padding: 30px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>